import request from '../../utils/request'
const app = getApp();
Page({
  data: {
    phone: ''
  },
  onShow() {
    const userInfo = app.globalData.userInfo || {}

    if (userInfo.phone) {
      this.setData({
        phone: userInfo.phone
      })
    }
  },

  onPhoneInput(e) {
    this.setData({ phone: e.detail.value });
  },
  onLogin() {
    const { phone } = this.data;
  
    if (!/^1\d{10}$/.test(phone)) {
      wx.showToast({ title: '请输入正确的手机号', icon: 'none' });
      return;
    }

      // 显示加载中提示
    wx.showLoading({
      title: '正在登录中...',
      mask: true // 防止用户点击其他地方
    })

  

    request({
      url: 'auth/login/usingPhone',
      method: 'POST',
      data: {
        cellphone: phone
      }
    })
      .then(res => {
        wx.setStorageSync('token', res.data.token);
    
        const app = getApp();
        app.globalData.userInfo.token = res.data.token;
        app.globalData.userInfo.phone = phone;
        this.onGoHome();
      })
      .catch(err => {
        console.error('登录失败', err);
        wx.hideLoading();
        setTimeout(() => {
          wx.showToast({
            title: err.message || '登录失败',
            icon: 'none',
            duration: 3000
          });
        }, 100); // 延迟 100ms，兼容安卓渲染慢
      })
      .finally(() => {
        // wx.hideLoading();
      });
  },
  

  onGoHome() {
    wx.reLaunch({
      url: '/pages/home/home'
    });
  }
  

});
